<!-- 费用记录 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属公司" prop="companyId">
        <el-tree-select v-model="queryParams.companyId" placeholder="请选择所属公司" clearable :data="treeList"
          :expand-on-click-node="false" :render-after-expand="false" @change="handleQuery" check-strictly
          :props="{ label: 'label' }" node-key="id" filterable />
      </el-form-item>
      <el-form-item label="用车人" prop="driverId">
        <el-input v-model="queryParams.driverId" placeholder="请输入用车人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="光伏板编号" prop="vehicleId">
        <el-input v-model="queryParams.vehicleId" placeholder="请输入光伏板编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="发生时间" prop="buyTime">
        <el-date-picker clearable v-model="queryParams.buyTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择发生时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['gwc:costRecord:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['gwc:costRecord:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column label="所属公司" align="center" prop="companyName"></el-table-column>
      <el-table-column label="用车人姓名" align="center" prop="driverName"></el-table-column>
      <el-table-column label="用车人联系电话" align="center" prop="contactNumber"></el-table-column>
      <el-table-column label="光伏板编号" align="center" prop="numberPlate"></el-table-column>
      <el-table-column label="发生时间" align="center" prop="buyTime" width="180"></el-table-column>
      <el-table-column label="费用类型" align="center" prop="costType">
        <template #default="scope">
          <dict-tag :options="sel_option.costType" :value="scope.row.costType" />
        </template>
      </el-table-column>
      <el-table-column label="费用名称" align="center" prop="costName">
        <template #default="scope">
          <dict-tag :options="sel_option.costName" :value="scope.row.costName" />
        </template>
      </el-table-column>
      <el-table-column label="金额(元)" align="center" prop="amountStr"></el-table-column>
      <el-table-column label="费用说明" align="center" prop="remarks"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['gwc:costRecord:edit']">修改</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['gwc:costRecord:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改费用记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px" class="sky-form-block">
        <el-form-item label="所属公司" prop="companyId">
          <el-tree-select v-model="form.companyId" placeholder="请选择所属公司" clearable :data="sel_option.companyId"
          :expand-on-click-node="false" :render-after-expand="false" check-strictly :props="{ label: 'label' }" node-key="id" filterable />
        </el-form-item>
        <el-form-item label="负责人" prop="driverId">
          <el-select v-model="form.driverId" filterable remote reserve-keyword placeholder="请输入负责人查询"
            :remote-method="remoteDriverMethod" :loading="remoteDriverLoading">
            <el-option v-for="item in sel_option.driverId" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="光伏板编号" prop="vehicleId">
          <el-select v-model="form.vehicleId" filterable remote reserve-keyword placeholder="请输入光伏板编号查询"
            :remote-method="remoteMethod" :loading="remoteLoading">
            <el-option v-for="item in sel_option.vehicleId" :key="item.id" :label="item.numberPlate" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="费用类型" prop="costType">
          <el-select v-model="form.costType" filterable clearable>
            <el-option v-for="item in sel_option.costType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费用名称" prop="costName">
          <el-select v-model="form.costName" filterable clearable>
            <el-option v-for="item in sel_option.costName" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间" prop="buyTime">
          <el-date-picker clearable v-model="form.buyTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择发生时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="费用说明" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入费用说明" />
        </el-form-item>
        <el-form-item label="金额(元)" prop="amountStr">
          <el-input v-model="form.amountStr" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="图片" prop="imageList">
          <ImageUpload :limit="1" :rank="0" ref="fileUpload" url='/app/vehicleApplication/uploadVoucher'
            :pictures='form.imageList || []' :disabled="formDisabled">
          </ImageUpload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/gwc/costRecord";
import { formatDate } from '@/utils/index'
import { getSearchCompanyListRole } from "@/api/system/dept";
import dayjs from "dayjs"
const { proxy } = getCurrentInstance();
const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const treeList = ref([])
getSearchCompanyListRole().then(res => {
  treeList.value = res.data
  sel_option.value.companyId = res.data
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
    companyId: null,
    driverId: null,
    vehicleId: null,
    costType: null,
    costName: null,
    buyTime: null,
    remarks: null,
    amountStr: null,
    imageList: null,
  },
  rules: {
    companyId: [
      { required: true, message: "所属部门不能为空", trigger: "blur" }
    ],
    costType: [
      { required: true, message: "费用类型不能为空", trigger: "blur" }
    ],
    costName: [
      { required: true, message: "费用名称不能为空", trigger: "blur" }
    ],
  }
});
const sel_option = ref({});
const { queryParams, form, rules } = toRefs(data);
let dictList = [];
sel_option.value = proxy.useDict.apply(this, [...dictList, "costType", "costName"]);

import { getVehicleList, getDriverList } from "@/api/tool/gen"
const remoteLoading = ref(true);
const remoteDriverLoading = ref(true);
const remoteMethod = (queryStr) => {
  remoteLoading.value = true
  if (queryStr) {
    getVehicleList({
      pageNum: 1,
      pageSize: 10,
      companyId: form.value.companyId, //公司id
      numberPlate: queryStr, //光伏板编号（支持模糊匹配）
    }).then((res) => {
      remoteLoading.value = false;
      sel_option.value.vehicleId = res.rows
    })
  }
}

const remoteDriverMethod = (queryStr) => {
  remoteDriverLoading.value = true
  if (queryStr) {
    getDriverList({
      pageNum: 1,
      pageSize: 10,
      companyId: form.value.companyId, //公司id
      name: queryStr,
    }).then((res) => {
      remoteDriverLoading.value = false;
      sel_option.value.driverId = res.rows;
    })
  }
}

/** 查询费用记录列表 */
function getList() {
  loading.value = true;
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    companyId: null,
    driverId: null,
    vehicleId: null,
    costType: null,
    costName: null,
    buyTime: null,
    remarks: null,
    amountStr: null,
    imageList: null,
    createTime: null,
    updateTime: null,
    updateBy: null,
    createBy: null
  };
  proxy.resetForm("recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加费用记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _recordId = row.recordId || ids.value
  getRecord(_recordId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改费用记录";
    sel_option.value.vehicleId = [
      {
        id: row.vehicleId,
        numberPlate: row.numberPlate,
      }
    ]
    sel_option.value.driverId = [
      {
        id: row.driverId,
        name: row.driverName,
      }
    ]
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.recordId != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value;
  proxy.$modal.confirm('是否确认删除费用记录编号为"' + _recordIds + '"的数据项？').then(function () {
    return delRecord(_recordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('gwc/costRecord/export', {
    ...queryParams.value
  }, `费用记录_${dayjs(new Date()).format("YYYY-MM-DD_HH:mm:ss")}.xlsx`)
}

getList();
</script>
